package com.mangguo.tingjian.account.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mangguo.tingjian.account.common.enums.UserConstant;
import com.mangguo.tingjian.account.dto.UserDto;
import com.mangguo.tingjian.account.dto.UserQueryReq;
import com.mangguo.tingjian.account.mapper.UserMapper;
import com.mangguo.tingjian.account.entity.User;
import com.mangguo.tingjian.account.security.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Optional;


@Service
@Transactional
@Slf4j
public class UserService {

   private final UserMapper userMapper;

   @Resource
   private PasswordEncoder passwordEncoder;

   public UserService(UserMapper userMapper) {
      this.userMapper = userMapper;
   }

   @Transactional(readOnly = true)
   public Optional<User> getUserWithAuthorities() {
      return Optional.of(userMapper.selectByUserName(SecurityUtils.getCurrentUsername().get()));
   }


   public boolean createUser(UserDto userDto){
      User operateUser = userMapper.selectByUserName(SecurityUtils.getCurrentUsername().get());
      User user = User.builder()
              .username(userDto.getUsername())
              .password(passwordEncoder.encode("123456"))
              .roleId(userDto.getDeptId())
              .deptId(userDto.getDeptId())
              .avatar(userDto.getAvatar())
              .email(userDto.getEmail())
              .trueName(userDto.getTrueName())
              .operateUserId(operateUser.getId())
              .operateTrueName(operateUser.getTrueName())
              .build();
      return userMapper.insert(user) > 0;
   }

   public boolean updateLoginTime(String userName, Date date){
      User user = userMapper.selectByUserName(userName);
      if(user == null){
         log.info("updateLoginTime user is not exists, userName:{}", userName);
         return false;
      }
      user.setLastLoginTime(date);
      return userMapper.updateById(user) > 0;
   }

   public boolean updateUser(UserDto userDto){
      User user = userMapper.selectByUserName(userDto.getUsername());
      if(user == null){
         log.info("updateUser user is not exists, userDto:{}", JSONObject.toJSONString(userDto));
         return false;
      }
      user.setRoleId(userDto.getRoleId());
      user.setDeptId(userDto.getDeptId());
      user.setTrueName(userDto.getTrueName());
      return userMapper.updateById(user) > 0;
   }

   /**
    * 禁用user
    * @param id
    * @return
    */
   public boolean validUser(Long id, Integer valid){
      User user = userMapper.selectById(id);
      if(user == null){
         log.info("disableUser user is not exists, id:{}, valid:{}", id, valid);
         return false;
      }
      user.setIsValid(valid);
      return userMapper.updateById(user) > 0;
   }

   /**
    * 删除用户
    * @param id
    * @return
    */
   public boolean deleteUser(Long id){
      User user = userMapper.selectById(id);
      if(user == null){
         log.info("deleteUser user is not exists, id:{}", id);
         return false;
      }

      user.setDeleteFlag(UserConstant.DeleteStatus.IS_DELETE.getStatus());
      return userMapper.deleteById(user.getId()) > 0;
   }

   public IPage<User> selecPage(UserQueryReq req){
      Page<User> page = new Page<>(req.getCurrent(), req.getSize(),true);
      User user = User.builder().deleteFlag(UserConstant.DeleteStatus.IS_NOT_DELETE.getStatus()).build();
      if(req.getUserName() != null && !req.getUserName().equals("")){
         user.setUsername(req.getUserName());
      }
      if(req.getDeptId() != null){
         user.setDeptId(req.getDeptId());
      }

      return userMapper.selectPage(page, new QueryWrapper<>(user));
   }

   public boolean updatePassWord(Long id, String password){
      User user = userMapper.selectById(id);
      if(user == null){
         log.info("updatePassWord user is null id:{}", id);
         return false;
      }
      user.setPassword(passwordEncoder.encode(password));
      return userMapper.updateById(user) > 0;
   }
}
